<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.loli.net/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"monocy.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":true,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":false,"top_n_per_article":5,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言不久前组内有大佬发布了一个 vue-cli3 的 dll 包，作为一个在 vue 项目内摸爬滚打的萌新，是时候该学习点儿新的技术了，于是在闲暇之余，我拷贝了一份代码，同时研究该如何从“零”开始编写一个 dll 包（该部分以 webpack 的 dllPlugin 作为例子）。">
<meta name="keywords" content="Vue,Webpack">
<meta property="og:type" content="article">
<meta property="og:title" content="vue-cli3 的快速插件开发">
<meta property="og:url" content="https://monocy.gitee.io/2019/05/09/vue-cli3-的快速插件开发/index.html">
<meta property="og:site_name" content="沐光">
<meta property="og:description" content="前言不久前组内有大佬发布了一个 vue-cli3 的 dll 包，作为一个在 vue 项目内摸爬滚打的萌新，是时候该学习点儿新的技术了，于是在闲暇之余，我拷贝了一份代码，同时研究该如何从“零”开始编写一个 dll 包（该部分以 webpack 的 dllPlugin 作为例子）。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2022-07-26T13:04:47.334Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue-cli3 的快速插件开发">
<meta name="twitter:description" content="前言不久前组内有大佬发布了一个 vue-cli3 的 dll 包，作为一个在 vue 项目内摸爬滚打的萌新，是时候该学习点儿新的技术了，于是在闲暇之余，我拷贝了一份代码，同时研究该如何从“零”开始编写一个 dll 包（该部分以 webpack 的 dllPlugin 作为例子）。">

<link rel="canonical" href="https://monocy.gitee.io/2019/05/09/vue-cli3-的快速插件开发/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>vue-cli3 的快速插件开发 | 沐光</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">沐光</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">记录在前端之路的点点滴滴</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">31</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">15</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/kazehaiya" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://monocy.gitee.io/2019/05/09/vue-cli3-的快速插件开发/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="蔡胤">
      <meta itemprop="description" content="Just do IT!">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="沐光">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          vue-cli3 的快速插件开发
        </h1>

        <div class="post-meta">
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-07-26 21:04:47" itemprop="dateModified" datetime="2022-07-26T21:04:47+08:00">2022-07-26</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a>
                </span>
            </span>

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2019/05/09/vue-cli3-的快速插件开发/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2019/05/09/vue-cli3-的快速插件开发/" itemprop="commentCount"></span>
    </a>
  </span>
  
  
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.4k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>3 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>不久前组内有大佬发布了一个 vue-cli3 的 dll 包，作为一个在 vue 项目内摸爬滚打的萌新，是时候该学习点儿新的技术了，于是在闲暇之余，我拷贝了一份代码，同时研究该如何从“零”开始编写一个 dll 包（该部分以 webpack 的 dllPlugin 作为例子）。</p>
<a id="more"></a>
<h3 id="了解文档"><a href="#了解文档" class="headerlink" title="了解文档"></a>了解文档</h3><p>通篇读完官网的文档，因为知识点比较多，并且没有详细的例子（指“傻瓜式教学式”），因此开发这第三方包的学习成本还是有一些的，特别是 webpack-chain 和 node 的部分知识，这里记录总结了一些关键的点。</p>
<h4 id="插件命名"><a href="#插件命名" class="headerlink" title="插件命名"></a>插件命名</h4><p>最开始命名文件夹时我并没有使用 <code>vue-cli-plugin-</code> 作为文件名前缀，结果可想而知，vue invoke 一直提示找不到该包的信息。于是我去看了看源码…… 在 <code>@vue/cli/lib/invoke.js</code> 内，其有一个关键的获取包 Id 的方法 <code>resolvePluginId</code>，该方法在 <code>@vue/cli-shared-utils/lib/pluginResolution.js</code>，源码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">exports.resolvePluginId = <span class="function"><span class="params">id</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// already full id</span></span><br><span class="line">  <span class="comment">// e.g. vue-cli-plugin-foo, @vue/cli-plugin-foo, @bar/vue-cli-plugin-foo</span></span><br><span class="line">  <span class="keyword">if</span> (pluginRE.test(id)) &#123;</span><br><span class="line">    <span class="keyword">return</span> id;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// scoped short</span></span><br><span class="line">  <span class="comment">// e.g. @vue/foo, @bar/foo</span></span><br><span class="line">  <span class="keyword">if</span> (id.charAt(<span class="number">0</span>) === <span class="string">'@'</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> scopeMatch = id.match(scopeRE);</span><br><span class="line">    <span class="keyword">if</span> (scopeMatch) &#123;</span><br><span class="line">      <span class="keyword">const</span> scope = scopeMatch[<span class="number">0</span>];</span><br><span class="line">      <span class="keyword">const</span> shortId = id.replace(scopeRE, <span class="string">''</span>);</span><br><span class="line">      <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;scope&#125;</span><span class="subst">$&#123;scope === <span class="string">'@vue/'</span> ? <span class="string">``</span> : <span class="string">`vue-`</span>&#125;</span>cli-plugin-<span class="subst">$&#123;shortId&#125;</span>`</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// default short</span></span><br><span class="line">  <span class="comment">// e.g. foo</span></span><br><span class="line">  <span class="keyword">return</span> <span class="string">`vue-cli-plugin-<span class="subst">$&#123;id&#125;</span>`</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>很明显，使用 vue invoke 时其只会寻找含有 <code>vue-cli-plugin-</code> 作为前缀的包，官网内在文档的最后部分有做对应的说明（这个是后来才看到的），原文如下：</p>
<blockquote>
<p>为了让一个 CLI 插件能够被其它开发者使用，你必须遵循 <code>vue-cli-plugin-&lt;name&gt;</code> 的命名约定将其发布到 npm 上。</p>
</blockquote>
<p>因此 <code>package.json</code> 的 <code>name</code> 字段符合规则即可。</p>
<h4 id="creator-和-service"><a href="#creator-和-service" class="headerlink" title="creator 和 service"></a>creator 和 service</h4><p>官网开篇就介绍了两个主要的部分：<code>@vue/cli</code> 和 <code>@vue/cli-service</code>，首先是 <code>@vue/cli</code> 部分，这里介绍了插件的目录结构，因此我们可以根据此来搭一个插件框架：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">vue-cli-plugin-xxx</span><br><span class="line">  ├── README.md</span><br><span class="line">  ├── generator</span><br><span class="line">  |  └── index.js</span><br><span class="line">  ├── index.js</span><br><span class="line">  ├── package.json</span><br><span class="line">  ├── prompts</span><br><span class="line">  |  └── index.js</span><br><span class="line">  ├── service</span><br><span class="line">  |  ├── config-file.js</span><br><span class="line">  |  └── regist-command.js</span><br><span class="line">  └── yarn.lock</span><br></pre></td></tr></table></figure>
<p>接下来就详细分析一下各部分的作用。</p>
<h4 id="generator"><a href="#generator" class="headerlink" title="generator"></a>generator</h4><h5 id="文档分析"><a href="#文档分析" class="headerlink" title="文档分析"></a>文档分析</h5><p>文档中有提到，插件内的 generator 将会在两种场景下被调用：</p>
<ul>
<li>在一个项目的初始化创建过程中，如果 CLI 插件作为项目创建 preset 的一部分被安装</li>
<li>插件在项目创建好之后通过 <code>vue invoke</code> 独立调用时被安装</li>
</ul>
<p>由于开发的第三方插件使用场景多数在于更改已安装的项目配置，<code>preset</code> 使用场景不是很多（创建项目时一般还是手动配置，大多数情况不会选择去生成一个 ~/.vuerc），因此这边仅处理使用手动调用 generator 的情况。</p>
<p>触发 <code>generator</code> 的方法有两种：</p>
<ul>
<li><code>vue invoke</code></li>
<li><code>vue add</code></li>
</ul>
<p>下面就简单介绍一下这两个命令的区别。</p>
<h5 id="vue-invoke-指令"><a href="#vue-invoke-指令" class="headerlink" title="vue invoke 指令"></a>vue invoke 指令</h5><p>此指令的适用情况为已经通过 yarn 或者 npm 将包安装至项目内，此时仅需要调用 vue invoke <packagename> 即可。</packagename></p>
<blockquote>
<p>注意：这里的 packageName 为不包含 <code>vue-cli-plugin-</code> 部分的剩余包名，比如：发布的包名为 <code>vue-cli-plugin-xxx</code>，那么此时使用命令即 <code>vue invoke xxx</code></p>
</blockquote>
<h5 id="vue-add"><a href="#vue-add" class="headerlink" title="vue add"></a>vue add</h5><p>此指令的使用情况为项目内还没有安装对应的包，使用方式同 <code>vue invoke</code></p>
<blockquote>
<p>注：如果包的源不对的话，请自己在后面加上包所在的 npm 源地址（ –registry <npm origin path> ）</npm></p>
</blockquote>
<h5 id="内容编写"><a href="#内容编写" class="headerlink" title="内容编写"></a>内容编写</h5><p>分析了这么多，重点还是 generator 内我们应该写点什么，它影响的是什么。好了，让我们来继续看文档(● ˃̶͈̀ ロ ˂̶͈́)੭ꠥ⁾⁾</p>
<p>generator 有三个参数，这里就不细赘了，因为这里不关注 preset 的配置，所以对我们来说，有用的部分就只有第一个参数 api。首先我们需要改动的部分便是项目内的 package.json 了，使用方法 <code>extendPackage</code> 即可，例子如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">// 修改 `package.json` 里的字段</span><br><span class="line">// vue 部分的内容可以不要</span><br><span class="line">module.exports = (api, options, rootOptions) =&gt; &#123;</span><br><span class="line">  // 修改 `package.json` 里的字段</span><br><span class="line">  api.extendPackage(&#123;</span><br><span class="line">    scripts: &#123;</span><br><span class="line">      test: &apos;vue-cli-service test&apos;</span><br><span class="line">    &#125;,</span><br><span class="line">    vue: &#123;</span><br><span class="line">      pluginOptions: &#123;</span><br><span class="line">        test: &#123;</span><br><span class="line">          // 需要预打包的部分</span><br><span class="line">          vendors: [],</span><br><span class="line">          // 输出文件名</span><br><span class="line">          outputName: &apos;vendor.dll.js&apos;,</span><br><span class="line">          // 输出地址</span><br><span class="line">          outputPath: &apos;./public/vendor&apos;,</span><br><span class="line">          // 是否调用 cleanWebpackPlugin</span><br><span class="line">          cleanCache: true</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>关于此处添加的 <code>vue</code> 字段在 invoke 后会自动补充至 vue.config.js 或者 package.json 内。</p>
<p>如果你配置了 promots 并且需要该部分的内容，那么可以使用第二个 options 参数去获取配置的内容。（配置 .vuerc 的方法没有尝试，因为解构 + 默认值 + prompts 已经足够了）</p>
<blockquote>
<p>如果需要配置模板方面的参考<a href="https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-service/generator/index.js" target="_blank" rel="noopener">官方源码</a>，感觉配合 prompts 写个模板插件也不错。</p>
</blockquote>
<blockquote>
<p>友情提示：render() 函数内为你的 template 模板基于当前文件夹所在的路径。</p>
</blockquote>
<h4 id="prompts"><a href="#prompts" class="headerlink" title="prompts"></a>prompts</h4><p>该部分其实在这个项目内并没有涉及，但还是要提一下。官方文档对于此部分在内建插件有详细的说明（官方插件），第三方插件提到过一点：</p>
<blockquote>
<p>这个文件应该导出一个用于 Inquirer.js 的<a href="https://github.com/SBoudrias/Inquirer.js#question" target="_blank" rel="noopener">问题</a>的数组。这些被解析的答案对象会作为选项被传递给插件的 generator。</p>
</blockquote>
<p>因此，如果需要的情况下，我们得通过数组的形式编写问答。例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = [</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'entry'</span>,</span><br><span class="line">    message: <span class="string">"What's the output file's name?"</span>,</span><br><span class="line">    type: <span class="string">'input'</span>,</span><br><span class="line">    <span class="keyword">default</span>: <span class="string">'vendor'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">];</span><br></pre></td></tr></table></figure>
<p>此部分的配置结果会在 generator 部分的第二个参数捕捉到。</p>
<h4 id="service"><a href="#service" class="headerlink" title="service"></a>service</h4><p>这部分就是配置的重点了,还是根据官网来吧，官网有提到 3 个命令： <code>chainWebpack</code>、<code>configureWebpack</code>、<code>registerCommand</code>。直接更改原有项目的配置并不是很好（除非你很有信心），因此我们可以使用 <code>configureWebpack</code> 来合并变更。</p>
<p>这部分总的来说做三件事：</p>
<ol>
<li>更改用户的 webpack 配置文件（也就是 vue.config.js）</li>
<li>向 cli-service 内注册指令</li>
<li>为注册的指令指定模式</li>
</ol>
<p>这里从简单的部分开始一一说明吧～（顺序：3、1、2）</p>
<h5 id="指定模式"><a href="#指定模式" class="headerlink" title="指定模式"></a>指定模式</h5><p>嗯，这个最简单了，毕竟官网文档内有，理由也就不赘述了，代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports.defaultModes = &#123;</span><br><span class="line">  &lt;your direct&gt;: <span class="xml"><span class="tag">&lt;<span class="name">target</span> <span class="attr">mode</span>&gt;</span></span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>
<p>其中 <code>your direct</code> 部分即先前的 generator 部分注册的 script 脚本内，在 <code>vue-cli-service</code> 后面的那个指，比如，先前写的是 <code>test</code>，那么这里注册的指令也是 <code>direct</code>，mode 就根据实际情况处理即可，一般使用 <code>production</code> 生产模式就没啥问题。</p>
<h5 id="更改用户的配置文件"><a href="#更改用户的配置文件" class="headerlink" title="更改用户的配置文件"></a>更改用户的配置文件</h5><p>这里就需要有 webpack-chain 的知识了。先看看 pluginAPI 内有些啥（<a href="https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-service/lib/PluginAPI.js" target="_blank" rel="noopener">传送门</a>）,可能会用到的一些方法包括：</p>
<ul>
<li>getCwd：获取当前的工作目录</li>
<li>resolve：相当于 path.resolve</li>
<li>registerCommand：注册指令（有三个参数！）</li>
<li>chainWebpack：链式调用 webpack</li>
<li>configureWebpack：用于合并 webpack</li>
<li>resolveChainableWebpackConfig：用于解析 webpack</li>
</ul>
<p>此处我们使用 <code>configureWebpack</code> 来更改配置，同时使用 <code>registerCommand</code> 来注册我们的命令。这里刚好对应的就是我们的两个文件 <code>config-file</code> 和 <code>regist-command.js</code> 了，对应开发即可。</p>
<h6 id="configureWebpack"><a href="#configureWebpack" class="headerlink" title="configureWebpack"></a>configureWebpack</h6><p>参考源码的写法，我们可以通过 options 参数获取 invoke 生成的 <code>vue.config.js</code> 里面的 <code>pluginOptions</code> 字段内的对应配置内容，配合 <code>api.configureWebpack</code> 来注入我们的 webpack 配置。粗略的写法为：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">api.configureWebpack(<span class="function"><span class="params">config</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 增一个 plugins</span></span><br><span class="line">  config.plugins</span><br><span class="line">    .push</span><br><span class="line">    <span class="comment">/* plugin 配置 */</span></span><br><span class="line">    ();</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h6 id="registerCommand"><a href="#registerCommand" class="headerlink" title="registerCommand"></a>registerCommand</h6><p>查看源码的写法，发现参数有三个，分别是：</p>
<ul>
<li>api: pluginAPI 实例</li>
<li>options: 用来添加配置说明</li>
<li>fn: 回调函数，用于触发执行的内容（比如运行一个 webpack 配置）</li>
</ul>
<p>官方的写法如下，我们可以据此模仿</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">api.registerCommand(</span><br><span class="line">  <span class="string">'test'</span>,</span><br><span class="line">  &#123;</span><br><span class="line">    description: <span class="string">'此为指令的说明'</span>, <span class="comment">// 指令意义</span></span><br><span class="line">    usage: <span class="string">'vue-cli-service test'</span>, <span class="comment">// 命令怎么用</span></span><br><span class="line">    options: &#123;</span><br><span class="line">      <span class="comment">/* 参数说明 */</span></span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="keyword">async</span> args =&gt; &#123;</span><br><span class="line">    <span class="comment">/* 可以写个 chain-webpack 然后调用，或者干点其它的 */</span></span><br><span class="line">  &#125;,</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h3 id="部分问题总结"><a href="#部分问题总结" class="headerlink" title="部分问题总结"></a>部分问题总结</h3><h4 id="1-demo-内的-dll-打包位置问题"><a href="#1-demo-内的-dll-打包位置问题" class="headerlink" title="1. demo 内的 dll 打包位置问题"></a>1. demo 内的 dll 打包位置问题</h4><p>使用默认的打包位置： <code>public/vendor</code> 会产生一个问题，就是 build 文件内会包含此 vendor 文件夹（public 文件夹内的内容默认会带至 dist 文件夹内），我们注入的一些配置不生效。</p>
<p>解决方法：将默认的 <code>public/vendor</code> 打包位置改改，只要不是生成在 public 文件夹内的都没问题，可看 vue-cli 官网的 public 部分的解释。</p>
<h4 id="2-webpack-函数"><a href="#2-webpack-函数" class="headerlink" title="2. webpack 函数"></a>2. webpack 函数</h4><p>目前第二个回调参数的使用场景不是很明确（其实不用回调也可以，外层关闭对应的 log 即可）</p>
<h4 id="3-configureWebpack-只能用-push"><a href="#3-configureWebpack-只能用-push" class="headerlink" title="3. configureWebpack 只能用 push?"></a>3. configureWebpack 只能用 push?</h4><p>我尝试过自己新创建一个 webpack-chain 然后返回（源码上好像会对返回值进行判断，如果有那么会调用 merge 方法），按理来说返回一个 config.toConfig() 应该 没问题，但是行不通，目前仍然用的是 push 方法</p>
<h3 id="demo"><a href="#demo" class="headerlink" title="demo"></a>demo</h3><p><a href="https://github.com/kazehaiya/vue-cli-plugin-demo" target="_blank" rel="noopener">传送门</a></p>
<h3 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h3><ul>
<li><a href="https://cli.vuejs.org/zh/dev-guide/plugin-dev.html#%E6%8F%92%E4%BB%B6%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97" target="_blank" rel="noopener">插件开发指南</a></li>
<li><a href="https://www.jianshu.com/p/7f0563dbe792" target="_blank" rel="noopener">Vue CLI 3 使用：插件和 Preset（二）</a></li>
<li><a href="https://blog.csdn.net/weixin_34268310/article/details/87119105" target="_blank" rel="noopener">使用 Webpack-chain 链式生成 webpack 配置</a></li>
<li><a href="https://segmentfault.com/a/1190000016389996" target="_blank" rel="noopener">如何使用 vue-cli 3 的 preset 打造基于 git repo 的前端项目模板</a></li>
<li><a href="https://github.com/vuetifyjs/vue-cli-plugin-vuetify" target="_blank" rel="noopener">vuetify</a></li>
<li><a href="https://segmentfault.com/q/1010000011753433" target="_blank" rel="noopener">webpack 函数参数</a></li>
<li><a href="https://segmentfault.com/a/1190000017547171#articleHeader5" target="_blank" rel="noopener">webpack chain 中文文档</a></li>
</ul>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>蔡胤
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://monocy.gitee.io/2019/05/09/vue-cli3-的快速插件开发/" title="vue-cli3 的快速插件开发">https://monocy.gitee.io/2019/05/09/vue-cli3-的快速插件开发/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"><i class="fa fa-tag"></i> Vue</a>
              <a href="/tags/Webpack/" rel="tag"><i class="fa fa-tag"></i> Webpack</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/05/08/提升项目的构建速度/" rel="prev" title="提升项目的构建速度">
      <i class="fa fa-chevron-left"></i> 提升项目的构建速度
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/05/19/深入了解-this/" rel="next" title="深入了解 this">
      深入了解 this <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#了解文档"><span class="nav-number">2.</span> <span class="nav-text">了解文档</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#插件命名"><span class="nav-number">2.1.</span> <span class="nav-text">插件命名</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#creator-和-service"><span class="nav-number">2.2.</span> <span class="nav-text">creator 和 service</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#generator"><span class="nav-number">2.3.</span> <span class="nav-text">generator</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#文档分析"><span class="nav-number">2.3.1.</span> <span class="nav-text">文档分析</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#vue-invoke-指令"><span class="nav-number">2.3.2.</span> <span class="nav-text">vue invoke 指令</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#vue-add"><span class="nav-number">2.3.3.</span> <span class="nav-text">vue add</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#内容编写"><span class="nav-number">2.3.4.</span> <span class="nav-text">内容编写</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#prompts"><span class="nav-number">2.4.</span> <span class="nav-text">prompts</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#service"><span class="nav-number">2.5.</span> <span class="nav-text">service</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#指定模式"><span class="nav-number">2.5.1.</span> <span class="nav-text">指定模式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#更改用户的配置文件"><span class="nav-number">2.5.2.</span> <span class="nav-text">更改用户的配置文件</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#configureWebpack"><span class="nav-number">2.5.2.1.</span> <span class="nav-text">configureWebpack</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#registerCommand"><span class="nav-number">2.5.2.2.</span> <span class="nav-text">registerCommand</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#部分问题总结"><span class="nav-number">3.</span> <span class="nav-text">部分问题总结</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-demo-内的-dll-打包位置问题"><span class="nav-number">3.1.</span> <span class="nav-text">1. demo 内的 dll 打包位置问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-webpack-函数"><span class="nav-number">3.2.</span> <span class="nav-text">2. webpack 函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-configureWebpack-只能用-push"><span class="nav-number">3.3.</span> <span class="nav-text">3. configureWebpack 只能用 push?</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#demo"><span class="nav-number">4.</span> <span class="nav-text">demo</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考文档"><span class="nav-number">5.</span> <span class="nav-text">参考文档</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="蔡胤"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">蔡胤</p>
  <div class="site-description" itemprop="description">Just do IT!</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">31</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/kazehaiya" title="GitHub → https://github.com/kazehaiya" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i></a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:c763416559@163.com" title="Mail → mailto:c763416559@163.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i></a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/Nora_Monocy" title="Weibo → https://weibo.com/Nora_Monocy" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i></a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://liujinkai.com/" title="http://liujinkai.com/" rel="noopener" target="_blank">凯凯刘</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://weekly.75team.com/" title="https://weekly.75team.com/" rel="noopener" target="_blank">奇舞周刊</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://75.team/post/list" title="https://75.team/post/list" rel="noopener" target="_blank">奇舞团博客</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://tech.meituan.com/" title="https://tech.meituan.com/" rel="noopener" target="_blank">美团技术团队</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://tech.youzan.com/" title="https://tech.youzan.com/" rel="noopener" target="_blank">有赞技术团队</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://kalacloud.com" title="https://kalacloud.com" rel="noopener" target="_blank">卡拉云</a>
        </li>
    </ul>
  </div>

      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn" rel="noopener" target="_blank">京ICP备2020036147号-1 </a>
      <img src="/images/beian.png" style="display: inline-block;"><a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=42011702000651" rel="noopener" target="_blank">鄂公网安备 42011702000651 号 </a>
  </div>

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-dragon"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蔡胤</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">101k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:32</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-pjax@0/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/medium-zoom@1/dist/medium-zoom.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script>
  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  




  <script src="/js/local-search.js"></script>












    <div id="pjax">
  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : true,
      notify     : true,
      appId      : 'GkgJm97N3UFm2mRb1eFcP2dn-gzGzoHsz',
      appKey     : 'kJ8tYUUkX4ifhWha8rjnxWS8',
      placeholder: "请不要吝惜你的笔头，来说点什么吧！",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : true,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

    </div>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/Epsilon2.1.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true,"scale":0.5},"react":{"opacity":0.7},"log":false});</script></body>
</html>
